package guoanmaker.operator.business.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.model.AppOutServerClass;
import guoanmaker.operator.business.model.OperatorServerClass;
import guoanmaker.operator.business.model.ProvideCommodity;
import guoanmaker.operator.business.model.ProviderBusiness;
import guoanmaker.operator.business.modelnobind.ProvideCommodityCount;
import guoanmaker.operator.business.repository.OperatorServerClassRepository;
import guoanmaker.operator.business.repository.ProvideCommodityRepository;
import guoanmaker.operator.business.repository.ProviderBusinessRepository;

/**
 *  
 *
 * @ClassName: OperatorServerClassService 
 * @Description: OperatorServerClassService 
 * @author: huZhaoyu 
 * @date 2017/6/28 下午2:56 
 */
@Service
public class OperatorServerClassService implements OperatorServerClassServiceInterface {
	@Autowired
    private  OperatorServerClassRepository operatorServerClassRepository;
	@Autowired
private ProvideCommodityRepository provideCommodityRepository;
	@Autowired
	private ProviderBusinessRepository providerBusinessRepository;
    @Override
    public Integer countAllById() {
        return operatorServerClassRepository.countAllByIdIsNotNull();
    }

    @Override
    public Page<OperatorServerClass> getServerClassByPageOrderByWeight(Integer page, Integer size) {
        return operatorServerClassRepository.findAll(new PageRequest(page, size, new Sort(Sort.Direction.DESC, "weight")));
    }

    @Autowired
    public OperatorServerClassService(OperatorServerClassRepository operatorServerClassRepository) {
        this.operatorServerClassRepository = operatorServerClassRepository;
    }

    @Override
    @Transactional
    public OperatorServerClass saveServerClass(OperatorServerClass operatorServerClass) {
        return operatorServerClassRepository.save(operatorServerClass);
    }

    @Override
    public List<OperatorServerClass> getAllServerClass() {
        return operatorServerClassRepository.findAll();
    }

    @Override
    public Page<OperatorServerClass> getAllServerClassByPage(Integer page, Integer size) {
        return operatorServerClassRepository.findAll(new PageRequest(page, size));
    }

    @Override
    @Transactional
    public void deleteServerClassById(String id) {
        operatorServerClassRepository.delete(id);
    }

    @Override
    public ArrayList<OperatorServerClass> getByParentServerId(String parentServerId) {
        return operatorServerClassRepository.findByParentServerId(parentServerId);
    }

    @Override
    public OperatorServerClass getServerClassById(String id) {
        return operatorServerClassRepository.findOne(id);
    }
    
    @PersistenceContext
	private EntityManager manager;
    
    @Override
    public List<AppOutServerClass> getAllServerClassByFirst() {
    	List<AppOutServerClass> apps=new ArrayList();
    	List<OperatorServerClass> serverfirsts=operatorServerClassRepository.findListBylevel();
    	if(serverfirsts.size()!=0){
    	for(OperatorServerClass os:serverfirsts){
    		List<OperatorServerClass> servertwos=operatorServerClassRepository.findByParentServerId(os.getId());
    		AppOutServerClass  appOutServerClass=new AppOutServerClass();
    		appOutServerClass.setOperatorServerClass(os);
    		appOutServerClass.setServerClas(servertwos);
    		apps.add(appOutServerClass);
    	}
    	}
    	return apps;
    	
    }

	@Override
	public List<OperatorServerClass> getAllServerClassByFirstlevel(String parentServerId) {
		// TODO Auto-generated method stub
		 Set<String> set=new HashSet<String>();
		 List<OperatorServerClass> sers=null;
		 if(parentServerId!=null&&!parentServerId.equals("")){
			 OperatorServerClass opetorserverid= operatorServerClassRepository.findOne(parentServerId);
			 if(opetorserverid.getServerLevel()==1){
				 sers= operatorServerClassRepository.findByParentServerId(parentServerId);
				 if(sers.size()>0){
					 for(OperatorServerClass ser:sers){
						
						 Set<String> setbus= new HashSet<String>();//商户总数量
						 Set<String> setallcom= new HashSet<String>();//商品总数量
						 Set<String> setoncom= new HashSet<String>();//上架商品数量
						 System.out.println("单次"+ser.getId());
						 List<ProviderBusiness>  pribus=providerBusinessRepository.findByseverid(ser.getId());
						 for(ProviderBusiness providebus:pribus){
							 setbus.add(providebus.getId());
						 }
						 List<OperatorServerClass> servers= operatorServerClassRepository.findByParentServerId(ser.getId());
						 if(servers.size()>0){
							 for(OperatorServerClass os:servers){
								 List<OperatorServerClass> seros= operatorServerClassRepository.findByParentServerId(os.getId());
								 if(seros.size()>0){
									 for(OperatorServerClass oss:seros){
										 List<OperatorServerClass> serosos= operatorServerClassRepository.findByParentServerId(oss.getId());
										 if(serosos.size()>0){
											 
										 }else{
											
											 List<ProvideCommodity> allcoms=provideCommodityRepository.selectByCommodityByserverIdAndstate(oss.getId());
												
											 for(ProvideCommodity pcc:allcoms){
												 setallcom.add(pcc.getId());
											 }
											 List<ProvideCommodity> oncoms=provideCommodityRepository.selectByserverIdAndstate(oss.getId());
											 
											 for(ProvideCommodity pccon:oncoms){
												 setoncom.add(pccon.getId());
											 }
										 }
									 }
									 
								 }else{
									
									 List<ProvideCommodity> allcoms=provideCommodityRepository.selectByCommodityByserverIdAndstate(os.getId());
										
									 for(ProvideCommodity pcc:allcoms){
										 setallcom.add(pcc.getId());
									 }
									 List<ProvideCommodity> oncoms=provideCommodityRepository.selectByserverIdAndstate(os.getId());
									 
									 for(ProvideCommodity pccon:oncoms){
										 setoncom.add(pccon.getId());
									 }
								 }
							 }
							 
						 }else{
							
							 List<ProvideCommodity> allcoms=provideCommodityRepository.selectByCommodityByserverIdAndstate(ser.getId());
							
								 for(ProvideCommodity pcc:allcoms){
									 setallcom.add(pcc.getId());
								 }
								 List<ProvideCommodity> oncoms=provideCommodityRepository.selectByserverIdAndstate(ser.getId());
								 
								 for(ProvideCommodity pccon:oncoms){
									 setoncom.add(pccon.getId());
								 }
							
							
							 
						 }
						 
					
						 ser.setBusinesssum(setbus.size()+"");
						 	ser.setComditysum(setallcom.size()+"");
						 	ser.setOncomditysum(setoncom.size()+"");
					 }
					 }
			 }
			 
			 if(opetorserverid.getServerLevel()==2){
				 sers= operatorServerClassRepository.findByParentServerId(parentServerId);
				 if(sers.size()>0){
					 for(OperatorServerClass ser:sers){
						
						 Set<String> setbus= new HashSet<String>();//商户总数量
						 Set<String> setallcom= new HashSet<String>();//商品总数量
						 Set<String> setoncom= new HashSet<String>();//上架商品数量
						 System.out.println("单次"+ser.getId());
						
						 List<OperatorServerClass> servers= operatorServerClassRepository.findByParentServerId(ser.getId());
						 if(servers.size()>0){
							 for(OperatorServerClass os:servers){
								 List<OperatorServerClass> seros= operatorServerClassRepository.findByParentServerId(os.getId());
								 if(seros.size()>0){
									
									 
								 }else{
									
									 List<ProvideCommodity> allcoms=provideCommodityRepository.selectByCommodityByserverIdAndstate(os.getId());
										
									 for(ProvideCommodity pcc:allcoms){
										 setallcom.add(pcc.getId());
									 }
									 List<ProvideCommodity> oncoms=provideCommodityRepository.selectByserverIdAndstate(os.getId());
									 
									 for(ProvideCommodity pccon:oncoms){
										 setoncom.add(pccon.getId());
									 }
								 }
							 }
							 
						 }else{
							
							 List<ProvideCommodity> allcoms=provideCommodityRepository.selectByCommodityByserverIdAndstate(ser.getId());
							
								 for(ProvideCommodity pcc:allcoms){
									 setallcom.add(pcc.getId());
								 }
								 List<ProvideCommodity> oncoms=provideCommodityRepository.selectByserverIdAndstate(ser.getId());
								 
								 for(ProvideCommodity pccon:oncoms){
									 setoncom.add(pccon.getId());
								 }
							
							
							 
						 }
						 
					
						 ser.setBusinesssum("0");
						 	ser.setComditysum(setallcom.size()+"");
						 	ser.setOncomditysum(setoncom.size()+"");
					 }
					 }
			 }
			 if(opetorserverid.getServerLevel()==3){
				 sers= operatorServerClassRepository.findByParentServerId(parentServerId);
				 if(sers.size()>0){
					 for(OperatorServerClass ser:sers){
						
						 Set<String> setbus= new HashSet<String>();//商户总数量
						 Set<String> setallcom= new HashSet<String>();//商品总数量
						 Set<String> setoncom= new HashSet<String>();//上架商品数量
						 System.out.println("单次"+ser.getId());
						
						 List<OperatorServerClass> servers= operatorServerClassRepository.findByParentServerId(ser.getId());
						 if(servers.size()>0){
							
						 }else{
							
							 List<ProvideCommodity> allcoms=provideCommodityRepository.selectByCommodityByserverIdAndstate(ser.getId());
							
								 for(ProvideCommodity pcc:allcoms){
									 setallcom.add(pcc.getId());
								 }
								 List<ProvideCommodity> oncoms=provideCommodityRepository.selectByserverIdAndstate(ser.getId());
								 
								 for(ProvideCommodity pccon:oncoms){
									 setoncom.add(pccon.getId());
								 }
							
							
							 
						 }
						 
					
						 ser.setBusinesssum("0");
						 	ser.setComditysum(setallcom.size()+"");
						 	ser.setOncomditysum(setoncom.size()+"");
					 }
					 }
			 }
			 
			
		 }else{
			 sers=operatorServerClassRepository.findListBylevel();
			
			 for(OperatorServerClass ser:sers){
				
				 Set<String> setbus= new HashSet<String>();//商户总数量
				 Set<String> setallcom= new HashSet<String>();//商品总数量
				 Set<String> setoncom= new HashSet<String>();//上架商品数量
				 	 List<OperatorServerClass> sertwos= operatorServerClassRepository.findByParentServerId(ser.getId());
				 	 if(sertwos.size()>0){
				 		for(OperatorServerClass sertwo:sertwos){
					 		List<ProviderBusiness>  pribus=providerBusinessRepository.findByseverid(sertwo.getId());
					 		if(pribus.size()>0){
					 			for(ProviderBusiness pbtwo:pribus){
					 				setbus.add(pbtwo.getId());
					 			}
					 			
					 		}
					 		 List<ProvideCommodity> allcoms=provideCommodityRepository.selectByCommodityByserverIdAndstate(sertwo.getId());
					 		if(allcoms.size()>0){
					 			for(ProvideCommodity pctwo:allcoms){
					 				setallcom.add(pctwo.getId());
					 			}
					 			
					 		}
					 		
					 		List<ProvideCommodity> coms=provideCommodityRepository.selectByserverIdAndstate(sertwo.getId());
					 		if(coms.size()>0){
					 			for(ProvideCommodity pctwoon:coms){
					 				setoncom.add(pctwoon.getId());
					 			}
					 			
					 		}
					 		 List<OperatorServerClass> serthrees= operatorServerClassRepository.findByParentServerId(sertwo.getId());
					 		 if(serthrees.size()>0){
					 			 for(OperatorServerClass serthree:serthrees){
					 				/*List<ProviderBusiness>  prithreebus=providerBusinessRepository.findByseverid(serthree.getId());
							 		if(prithreebus.size()>0){
							 			allbusnum+=prithreebus.size();
							 		}*/
							 		
							 		 List<ProvideCommodity> allcomthrees=provideCommodityRepository.selectByCommodityByserverIdAndstate(serthree.getId());
								 		if(allcomthrees.size()>0){
								 			for(ProvideCommodity pcthree:allcomthrees){
								 				setallcom.add(pcthree.getId());
								 			}
								 			
								 		}
								 		
								 		List<ProvideCommodity> oncomthrees=provideCommodityRepository.selectByserverIdAndstate(serthree.getId());
								 		if(oncomthrees.size()>0){
								 			for(ProvideCommodity pcthreeon:oncomthrees){
								 				setoncom.add(pcthreeon.getId());
								 			}
								 			
								 		}
							 		 List<OperatorServerClass> serfours= operatorServerClassRepository.findByParentServerId(serthree.getId());
							 		 if(serfours.size()>0){
							 			 for(OperatorServerClass serfour:serfours){
							 			/*List<ProviderBusiness>  prifourbus=providerBusinessRepository.findByseverid(serfour.getId()); 
							 			if(prifourbus.size()>0){
							 				
								 			allbusnum+=prifourbus.size();
								 		}*/
							 			
							 			 List<ProvideCommodity> allcomfours=provideCommodityRepository.selectByCommodityByserverIdAndstate(serfour.getId());
									 		if(allcomfours.size()>0){
									 			for(ProvideCommodity pcfour:allcomfours){
									 				setallcom.add(pcfour.getId());
									 			}
									 			
									 		}
									 		
									 		List<ProvideCommodity> oncomfours=provideCommodityRepository.selectByserverIdAndstate(serfour.getId());
									 		if(oncomfours.size()>0){
									 			for(ProvideCommodity pcfouron:oncomfours){
									 				setoncom.add(pcfouron.getId());
									 			}
									 			
									 		}
							 			}
							 		 }
							 		
					 			 }
					 			
					 		 }
					 		
					 	 }
				 	 }
				 	 
					
				 	
				 
				 	ser.setBusinesssum(setbus.size()+"");
				 	ser.setComditysum(setallcom.size()+"");
				 	ser.setOncomditysum(setoncom.size()+"");
				 	
				 	 
				 	 
			 }
			 
		 }
		 
		
		 
		 
		 
		 
		 return sers;
		 
	}
	
	
	 @Override
	 public void aaa(String serverId){
		OperatorServerClass serverClass=operatorServerClassRepository.findOne(serverId);//通过分类id获取分类对象
		List<String> ids=new ArrayList<>();
		if(serverClass!=null){
			if(serverClass.getServerLevel()==1){
				//查询二级基础数据
				List<OperatorServerClass> twoServers=operatorServerClassRepository.findAllByParentServerId(serverId);
				if(twoServers.size()>0){
					for(int i=0;i<twoServers.size();i++){
						String twoServerId=twoServers.get(i).getId();//二级id
						List<OperatorServerClass> threeServers=operatorServerClassRepository.findAllByParentServerId(twoServerId);
						if(threeServers.size()>0){//如果二级下面有三级
							for(int k=0;k<threeServers.size();k++){
								String threeServerId=threeServers.get(i).getId();//三级id
								List<OperatorServerClass> fourServers=operatorServerClassRepository.findAllByParentServerId(threeServerId);
								if(fourServers.size()>0){
									for(int j=0;j<fourServers.size();j++){
										String fourServerId=fourServers.get(i).getId();//三级id
										ids.add(fourServerId);
									}
								}else{
									ids.add(threeServerId);
								}
							}
						}else{
							ids.add(twoServerId);
						}
					}
				}
			}
		}
		String jpql="select new guoanmaker.operator.business.modelnobind.ProvideCommodityCount(b.businessName,t.commodityState,count(t.id))"
				+ " from ProvideCommodity t left join t.serviceType sc left join t.providerBusiness b ";
		String idStr=getServiceType(ids);//获取id格式串
		System.out.println("获取的id串："+idStr);
		jpql=jpql+"where  sc.id in ("+idStr+")  group by b.id,t.commodityState";
		Query query=manager.createQuery(jpql);//查询商品列表
		List<ProvideCommodityCount> commodityCounts=query.getResultList();
		System.out.println("长度:"+commodityCounts.size());
	 }
	
	
	 @Override
	    public List<OperatorServerClass> getAllServerClassFirstLevel() {
	        return operatorServerClassRepository.selectByOneServerclass();
	    }
	 
	 @Override
	    public List<OperatorServerClass> getAllServerClassTwoLevel() {
	        return operatorServerClassRepository.selectByTwoServerclass();
	    }
	 
	 /**
		 * 获取服务类型id串
		 * @author baixsh
		 * @param  ids(类型主键集合)
		 * */
		public static String getServiceType(List<String> ids){
			String str="";
			if(ids!=null){
				for(int k=0;k<ids.size();k++){
					if(k==0){
						str=str+"'"+ids.get(k)+"'";
					}else{
						str=str+",'"+ids.get(k)+"'";
					}
				}
			}
			return str;
		}

	@Override
	public Map selectValitaByid(String serverid) {
		Map<String,Object> remap=new HashMap<String ,Object>();
		Integer a=0;
		String mes="";
		List<ProvideCommodity> procoms=provideCommodityRepository.selectByCommodityByserverIdAndstate(serverid);
		if(procoms.size()>0){
			a=1;//产品使用中，不能删除
			mes="产品使用中，不能删除";
		}else{
			List<ProviderBusiness> probus=providerBusinessRepository.selectByServerId(serverid);
			if(probus.size()>0){
				a=2;//商户使用中
				mes="商户使用中，不能删除";
			}else{
				ArrayList<OperatorServerClass> operclass=operatorServerClassRepository.findAllByParentServerId(serverid);
				if(operclass.size()>0){
					a=3;//服务下有子项
					mes="服务下有子项，不能删除";
				}else{
					
					OperatorServerClass op=operatorServerClassRepository.findOne(serverid);
					if(null!=op){
						op.setDeleteState("1");
						operatorServerClassRepository.save(op);
						a=4;//删除成功
						mes="删除成功";
					}
					
				}
			}
		}
		
		remap.put("a",a);
		remap.put("mes", mes);
		return	remap;
		
	}

}
